package com.example.demo.controller;

import com.example.demo.dao.SysUserDao;
import com.example.demo.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ligh
 * 2021/7/8
 * UserController
 **/
@RestController
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("select")
    public List select(SysUser sysUser) throws Exception{
        List<SysUser> list = sysUserDao.select(sysUser);
        logger.info("增加前的user长度"+ list.size());
        this.addByField(list, SysUser.class);
        this.addByMothod(list, SysUser.class);
        logger.info("增加后的user长度"+ list.size());


        list.stream().forEach( a -> {
            if("admin".equals(a.getLoginName())){
                a.setIndex(12);
            }
        });

        //java8 list转化为list<String>
        List<Integer> integerList = list.stream().map(a -> a.getIndex()).collect(Collectors.toList());
        logger.info(integerList.toString());
        //java8 list转化为map
        Map<Integer, String> map = list.stream()
                //.filter(a -> a.getIndex() != null)
                .filter(a -> a.getLoginName() != null).collect(Collectors.toMap(a -> a.getIndex(), b -> b.getLoginName(), (a, b) -> b));
        logger.info(map.toString());
        return  list;
    }

    /**
     * 通过反射方法给list新增对象
     * @param list
     * @param c
     * @param <T>
     * @throws Exception
     */
    private <T> void addByMothod(List<T> list, Class c) throws Exception{
        T t = (T)c.newInstance();
        Method setIndex = c.getDeclaredMethod("setIndex", Integer.class);
        setIndex.invoke(t, 1);
        list.add(t);
    }

    /**
     * 通过反射属性给list新增对象
     * @param list
     * @param c
     * @param <T>
     * @throws Exception
     */
    private <T> void addByField(List<T> list, Class c) throws Exception{
        T t = (T)c.newInstance();
        Field field = c.getDeclaredField("index");
        field.setAccessible(true);
        field.set(t, 100);
        list.add(t);
    }

    @Autowired
    SysUserDao sysUserDao;
}
